package com.elink.enginerring.common;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.elink.enginerring.util.JSONUtil;

/**
 * 公共接口
 * @author hxjxiaojun
 * 
 */
@Controller
@RequestMapping("/common")
@ResponseBody
public class CommonController {
	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	@SuppressWarnings({ "deprecation" })
	@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
	public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
		String fileName = file.getOriginalFilename();
		String suffix = "";
		String newFileName = "";
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			suffix = fileName.substring(index);
		}
		Date d = new Date();
		int year = d.getYear()+1900;
		int month = d.getMonth()+1;
		int day = d.getDate();
		String basePath = year+month+day +"/"+d.getTime();
		
	     newFileName = "file/" +basePath + suffix;
		 String path = Constant.WEB_SERVER_PATH+"/" + newFileName;
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
			String url = Constant.WEB_SERVER_URL +"/"+ newFileName;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("url",url);
			map.put("size",file.getSize());
			return JSONUtil.getJSON(ErrorType.SUCCESS, map);
		} catch (IOException e) {
			return JSONUtil.getJSON(ErrorType.HANDLE_FILE_ERROR);
		}
	}

}